<template>
  <div class="message-center-page">
    <div class="container">
      <div class="page-header">
        <h1>消息中心</h1>
        <div class="page-actions">
          <el-button
            v-if="selectedMessages.length > 0"
            @click="handleBatchRead"
            :loading="batchLoading"
          >
            标记已读 ({{ selectedMessages.length }})
          </el-button>
          <el-button
            v-if="selectedMessages.length > 0"
            type="danger"
            @click="handleBatchDelete"
            :loading="batchLoading"
          >
            批量删除 ({{ selectedMessages.length }})
          </el-button>
          <el-button @click="toggleSelectMode">
            {{ isSelectMode ? '取消' : '管理' }}
          </el-button>
          <el-button @click="markAllAsRead" v-if="totalUnread > 0">
            全部已读
          </el-button>
        </div>
      </div>

      <!-- 消息统计 -->
      <div class="message-stats">
        <div class="stat-item">
          <div class="stat-number">{{ totalMessages }}</div>
          <div class="stat-label">总消息</div>
        </div>
        <div class="stat-item">
          <div class="stat-number unread">{{ totalUnread }}</div>
          <div class="stat-label">未读</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ todayMessages }}</div>
          <div class="stat-label">今日新增</div>
        </div>
      </div>

      <!-- 消息分类标签 -->
      <div class="filter-section">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane name="all">
            <template #label>
              全部
              <el-badge
                v-if="totalUnread > 0"
                :value="totalUnread"
                :max="99"
                class="tab-badge"
              />
            </template>
          </el-tab-pane>
          <el-tab-pane name="system">
            <template #label>
              系统消息
              <el-badge
                v-if="unreadCounts.system > 0"
                :value="unreadCounts.system"
                :max="99"
                class="tab-badge"
              />
            </template>
          </el-tab-pane>
          <el-tab-pane name="order">
            <template #label>
              订单消息
              <el-badge
                v-if="unreadCounts.order > 0"
                :value="unreadCounts.order"
                :max="99"
                class="tab-badge"
              />
            </template>
          </el-tab-pane>
          <el-tab-pane name="activity">
            <template #label>
              活动通知
              <el-badge
                v-if="unreadCounts.activity > 0"
                :value="unreadCounts.activity"
                :max="99"
                class="tab-badge"
              />
            </template>
          </el-tab-pane>
          <el-tab-pane name="service">
            <template #label>
              服务通知
              <el-badge
                v-if="unreadCounts.service > 0"
                :value="unreadCounts.service"
                :max="99"
                class="tab-badge"
              />
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索消息内容"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" v-loading="loading">
        <div v-if="messages.length === 0 && !loading" class="empty-state">
          <el-empty 
            :image-size="120"
            :description="searchKeyword ? '未找到相关消息' : '暂无消息'"
          >
            <el-button type="primary" @click="goToHome" v-if="!searchKeyword">
              去首页看看
            </el-button>
          </el-empty>
        </div>

        <div
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="{
            'unread': !message.isRead,
            'selected': selectedMessages.includes(message.id),
            'urgent': message.priority === 'high'
          }"
          @click="handleMessageClick(message)"
        >
          <div class="item-checkbox" v-if="isSelectMode" @click.stop>
            <el-checkbox
              :model-value="selectedMessages.includes(message.id)"
              @change="handleMessageSelect(message.id, $event)"
            />
          </div>

          <div class="message-icon">
            <el-icon :size="24" :color="getMessageIconColor(message.type)">
              <component :is="getMessageIcon(message.type)" />
            </el-icon>
            <div v-if="message.priority === 'high'" class="urgent-indicator">!</div>
          </div>

          <div class="message-content">
            <div class="message-header">
              <h3 class="message-title">
                {{ message.title }}
                <el-tag v-if="message.priority === 'high'" type="danger" size="small">
                  紧急
                </el-tag>
              </h3>
              <div class="message-meta">
                <el-tag
                  :type="getMessageTypeTag(message.type)"
                  size="small"
                >
                  {{ getMessageTypeText(message.type) }}
                </el-tag>
                <span class="message-time">{{ formatDate(message.createdAt) }}</span>
              </div>
            </div>

            <p class="message-summary">{{ message.content }}</p>

            <!-- 消息附加信息 -->
            <div class="message-extras" v-if="message.extras">
              <div v-if="message.extras.orderNumber" class="extra-item">
                <span class="extra-label">订单号：</span>
                <span class="extra-value">{{ message.extras.orderNumber }}</span>
              </div>
              <div v-if="message.extras.amount" class="extra-item">
                <span class="extra-label">金额：</span>
                <span class="extra-value amount">¥{{ message.extras.amount }}</span>
              </div>
            </div>

            <!-- 消息操作按钮 -->
            <div class="message-footer" v-if="message.actions?.length">
              <el-button
                v-for="action in message.actions"
                :key="action.type"
                :type="action.type === 'primary' ? 'primary' : 'default'"
                size="small"
                @click.stop="handleAction(message, action)"
              >
                {{ action.text }}
              </el-button>
            </div>
          </div>

          <div class="message-actions" v-if="!isSelectMode">
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button circle size="small">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :command="{ action: 'read', message }"
                    v-if="!message.isRead"
                  >
                    标记已读
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'unread', message }"
                    v-else
                  >
                    标记未读
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'pin', message }"
                    v-if="!message.isPinned"
                  >
                    置顶消息
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'unpin', message }"
                    v-else
                  >
                    取消置顶
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'delete', message }"
                    divided
                  >
                    删除消息
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <div class="unread-indicator" v-if="!message.isRead"></div>
          <div class="pinned-indicator" v-if="message.isPinned">
            <el-icon><Star /></el-icon>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button @click="loadMore" :loading="loadingMore">
          加载更多
        </el-button>
      </div>
    </div>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="showMessageDialog"
      :title="selectedMessage?.title"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <div class="message-detail" v-if="selectedMessage">
        <div class="detail-header">
          <div class="detail-meta">
            <el-tag
              :type="getMessageTypeTag(selectedMessage.type)"
              size="small"
            >
              {{ getMessageTypeText(selectedMessage.type) }}
            </el-tag>
            <span class="detail-time">{{ formatDate(selectedMessage.createdAt) }}</span>
            <el-tag v-if="selectedMessage.priority === 'high'" type="danger" size="small">
              紧急
            </el-tag>
          </div>
        </div>

        <div class="detail-content">
          <div v-html="selectedMessage.htmlContent || selectedMessage.content"></div>
        </div>

        <!-- 消息附加信息详情 -->
        <div class="detail-extras" v-if="selectedMessage.extras">
          <el-descriptions :column="2" border>
            <el-descriptions-item 
              v-if="selectedMessage.extras.orderNumber"
              label="订单号"
            >
              {{ selectedMessage.extras.orderNumber }}
            </el-descriptions-item>
            <el-descriptions-item 
              v-if="selectedMessage.extras.amount"
              label="金额"
            >
              ¥{{ selectedMessage.extras.amount }}
            </el-descriptions-item>
            <el-descriptions-item 
              v-if="selectedMessage.extras.merchantName"
              label="商家"
            >
              {{ selectedMessage.extras.merchantName }}
            </el-descriptions-item>
            <el-descriptions-item 
              v-if="selectedMessage.extras.serviceName"
              label="服务"
            >
              {{ selectedMessage.extras.serviceName }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 附件 -->
        <div class="detail-attachments" v-if="selectedMessage.attachments?.length">
          <h4>附件</h4>
          <div class="attachment-list">
            <div
              v-for="attachment in selectedMessage.attachments"
              :key="attachment.id"
              class="attachment-item"
              @click="downloadAttachment(attachment)"
            >
              <el-icon><Document /></el-icon>
              <span>{{ attachment.name }}</span>
              <span class="attachment-size">{{ formatFileSize(attachment.size) }}</span>
            </div>
          </div>
        </div>

        <!-- 相关链接 -->
        <div class="detail-links" v-if="selectedMessage.links?.length">
          <h4>相关链接</h4>
          <div class="link-list">
            <el-link
              v-for="link in selectedMessage.links"
              :key="link.url"
              :href="link.url"
              target="_blank"
              type="primary"
            >
              {{ link.title }}
            </el-link>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showMessageDialog = false">关闭</el-button>
          <el-button
            v-if="selectedMessage && !selectedMessage.isRead"
            type="primary"
            @click="markAsRead(selectedMessage)"
          >
            标记已读
          </el-button>
          <el-button
            v-if="selectedMessage?.actions?.length"
            type="primary"
            @click="handleAction(selectedMessage, selectedMessage.actions[0])"
          >
            {{ selectedMessage.actions[0].text }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  ShoppingBag,
<<<<<<< HEAD
  Gift,
=======
  Present,
>>>>>>> c61637f (所有前后端正常登录)
  Warning,
  InfoFilled,
  MoreFilled,
  Document,
  Search,
  Star,
  Service
} from '@element-plus/icons-vue'
import { messageApi } from '@/services/api'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 数据定义
const messages = ref([])
const loading = ref(true)
const loadingMore = ref(false)
const batchLoading = ref(false)
const activeTab = ref('all')
const isSelectMode = ref(false)
const selectedMessages = ref([])
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(20)
const showMessageDialog = ref(false)
const selectedMessage = ref(null)
const searchKeyword = ref('')
const searchTimer = ref(null)

const unreadCounts = reactive({
  system: 0,
  order: 0,
  activity: 0,
  service: 0
})

const messageStats = reactive({
  total: 0,
  unread: 0,
  today: 0
})

// 计算属性
const totalUnread = computed(() => {
  return Object.values(unreadCounts).reduce((sum, count) => sum + count, 0)
})

const totalMessages = computed(() => messageStats.total)
const todayMessages = computed(() => messageStats.today)

// 生命周期
onMounted(() => {
  fetchMessages()
  fetchUnreadCounts()
  fetchMessageStats()
  
  // 定时刷新未读消息数量
  setInterval(() => {
    fetchUnreadCounts()
  }, 30000) // 30秒刷新一次
})

// 方法定义
const fetchMessages = async (reset = true) => {
  try {
    if (reset) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }

    const response = await messageApi.getMessageList({
      type: activeTab.value === 'all' ? undefined : activeTab.value,
      page: page.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })

    const { data, total } = response.data
    
    if (reset) {
      messages.value = data || []
    } else {
      messages.value.push(...(data || []))
    }

    hasMore.value = messages.value.length < total
  } catch (error) {
    console.error('获取消息列表失败:', error)
    
    // 使用模拟数据
    const mockMessages = [
      {
        id: 1,
        type: 'order',
        title: '订单支付成功',
        content: '您的订单 #202412280001 已支付成功，商家正在准备服务，请耐心等待。',
        isRead: false,
        isPinned: false,
        priority: 'normal',
        createdAt: new Date(),
        extras: {
          orderNumber: '202412280001',
          amount: 68,
          merchantName: '专业洗护店',
          serviceName: '高档衣物干洗'
        },
        actions: [
          { type: 'primary', text: '查看订单', action: 'view_order', orderId: '1' }
        ]
      },
      {
        id: 2,
        type: 'system',
        title: '系统升级通知',
        content: '为了给您提供更好的服务体验，系统将于今晚23:00-01:00进行升级维护，期间可能无法正常使用。',
        isRead: true,
        isPinned: true,
        priority: 'high',
        createdAt: new Date(Date.now() - 86400000),
        actions: []
      },
      {
        id: 3,
        type: 'activity',
        title: '新用户福利',
        content: '恭喜您成为新用户！专属优惠券已发放到您的账户，快去使用吧！',
        isRead: false,
        isPinned: false,
        priority: 'normal',
        createdAt: new Date(Date.now() - 3600000),
        actions: [
          { type: 'primary', text: '查看优惠券', action: 'view_coupons' }
        ]
      }
    ]
    
    if (reset) {
      messages.value = mockMessages
    }
    
    ElMessage.error('获取消息列表失败，显示模拟数据')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const fetchUnreadCounts = async () => {
  try {
    const response = await messageApi.getUnreadCounts()
    Object.assign(unreadCounts, response.data)
    
    // 更新用户store中的未读消息数
    userStore.setUnreadCount(totalUnread.value)
  } catch (error) {
    console.error('获取未读消息数量失败:', error)
    // 使用模拟数据
    Object.assign(unreadCounts, {
      system: 1,
      order: 2,
      activity: 1,
      service: 0
    })
    userStore.setUnreadCount(4)
  }
}

const fetchMessageStats = async () => {
  try {
    const response = await messageApi.getMessageStats()
    Object.assign(messageStats, response.data)
  } catch (error) {
    console.error('获取消息统计失败:', error)
    // 使用模拟数据
    Object.assign(messageStats, {
      total: 15,
      unread: 4,
      today: 3
    })
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  selectedMessages.value = []
  fetchMessages()
}

const handleSearch = () => {
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  
  searchTimer.value = setTimeout(() => {
    fetchMessages()
  }, 500)
}

const toggleSelectMode = () => {
  isSelectMode.value = !isSelectMode.value
  selectedMessages.value = []
}

const handleMessageSelect = (id, checked) => {
  if (checked) {
    selectedMessages.value.push(id)
  } else {
    const index = selectedMessages.value.indexOf(id)
    if (index > -1) {
      selectedMessages.value.splice(index, 1)
    }
  }
}

const handleMessageClick = (message) => {
  if (isSelectMode.value) return
  
  selectedMessage.value = message
  showMessageDialog.value = true
  
  // 如果消息未读，自动标记为已读
  if (!message.isRead) {
    markAsRead(message, false)
  }
}

const handleBatchRead = async () => {
  try {
    batchLoading.value = true
    await messageApi.markMessagesAsRead(selectedMessages.value)
    
    // 更新本地状态
    messages.value.forEach(msg => {
      if (selectedMessages.value.includes(msg.id)) {
        msg.isRead = true
      }
    })
    
    ElMessage.success('批量标记已读成功')
    selectedMessages.value = []
    isSelectMode.value = false
    fetchUnreadCounts()
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  } finally {
    batchLoading.value = false
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？`,
      '批量删除消息',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    batchLoading.value = true
    await messageApi.deleteMessages(selectedMessages.value)
    
    // 更新本地状态
    messages.value = messages.value.filter(msg => !selectedMessages.value.includes(msg.id))
    
    ElMessage.success('批量删除成功')
    selectedMessages.value = []
    isSelectMode.value = false
    fetchUnreadCounts()
    fetchMessageStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchLoading.value = false
  }
}

const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要将所有未读消息标记为已读吗？',
      '全部已读',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await messageApi.markAllAsRead()
    
    // 更新本地状态
    messages.value.forEach(msg => {
      msg.isRead = true
    })
    
    ElMessage.success('所有消息已标记为已读')
    fetchUnreadCounts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('全部已读失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleCommand = async ({ action, message }) => {
  switch (action) {
    case 'read':
      await markAsRead(message)
      break
    case 'unread':
      await markAsUnread(message)
      break
    case 'pin':
      await pinMessage(message)
      break
    case 'unpin':
      await unpinMessage(message)
      break
    case 'delete':
      await deleteMessage(message)
      break
  }
}

const markAsRead = async (message, showMessage = true) => {
  try {
    await messageApi.markAsRead(message.id)
    message.isRead = true
    fetchUnreadCounts()
    if (showMessage) {
      ElMessage.success('已标记为已读')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    if (showMessage) {
      ElMessage.error('标记已读失败')
    }
  }
}

const markAsUnread = async (message) => {
  try {
    await messageApi.markAsUnread(message.id)
    message.isRead = false
    fetchUnreadCounts()
    ElMessage.success('已标记为未读')
  } catch (error) {
    console.error('标记未读失败:', error)
    ElMessage.error('标记未读失败')
  }
}

const pinMessage = async (message) => {
  try {
    await messageApi.pinMessage(message.id)
    message.isPinned = true
    ElMessage.success('消息已置顶')
  } catch (error) {
    console.error('置顶消息失败:', error)
    ElMessage.error('置顶失败')
  }
}

const unpinMessage = async (message) => {
  try {
    await messageApi.unpinMessage(message.id)
    message.isPinned = false
    ElMessage.success('已取消置顶')
  } catch (error) {
    console.error('取消置顶失败:', error)
    ElMessage.error('操作失败')
  }
}

const deleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除消息"${message.title}"吗？`,
      '删除消息',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await messageApi.deleteMessage(message.id)
    
    // 更新本地状态
    const index = messages.value.findIndex(msg => msg.id === message.id)
    if (index > -1) {
      messages.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
    fetchUnreadCounts()
    fetchMessageStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error('删除消息失败')
    }
  }
}

const handleAction = (message, action) => {
  // 处理消息中的操作按钮
  switch (action.action) {
    case 'view_order':
      router.push(`/orders/${action.orderId}`)
      break
    case 'view_coupons':
      router.push('/coupons')
      break
    case 'view_activity':
      router.push(`/activities/${action.activityId}`)
      break
    default:
      console.log('未知操作:', action)
  }
}

const loadMore = () => {
  page.value++
  fetchMessages(false)
}

const goToHome = () => {
  router.push('/home')
}

const handleCloseDialog = () => {
  showMessageDialog.value = false
  selectedMessage.value = null
}

const downloadAttachment = (attachment) => {
  // 下载附件
  window.open(attachment.url, '_blank')
}

const formatFileSize = (size) => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  return (size / (1024 * 1024)).toFixed(1) + ' MB'
}

const getMessageIcon = (type) => {
  const iconMap = {
    system: InfoFilled,
    order: ShoppingBag,
<<<<<<< HEAD
    activity: Gift,
=======
    activity: Present,
>>>>>>> c61637f (所有前后端正常登录)
    service: Service,
    warning: Warning
  }
  return iconMap[type] || Bell
}

const getMessageIconColor = (type) => {
  const colorMap = {
    system: '#409eff',
    order: '#67c23a',
    activity: '#e6a23c',
    service: '#909399',
    warning: '#f56c6c'
  }
  return colorMap[type] || '#909399'
}

const getMessageTypeTag = (type) => {
  const tagMap = {
    system: 'info',
    order: 'success',
    activity: 'warning',
    service: '',
    warning: 'danger'
  }
  return tagMap[type] || 'info'
}

const getMessageTypeText = (type) => {
  const textMap = {
    system: '系统消息',
    order: '订单消息',
    activity: '活动通知',
    service: '服务通知',
    warning: '警告通知'
  }
  return textMap[type] || '未知类型'
}

const formatDate = (date) => {
  const now = dayjs()
  const msgDate = dayjs(date)
  
  if (now.diff(msgDate, 'minute') < 1) {
    return '刚刚'
  } else if (now.diff(msgDate, 'hour') < 1) {
    return msgDate.fromNow()
  } else if (now.diff(msgDate, 'day') === 0) {
    return msgDate.format('HH:mm')
  } else if (now.diff(msgDate, 'day') === 1) {
    return '昨天 ' + msgDate.format('HH:mm')
  } else if (now.diff(msgDate, 'year') === 0) {
    return msgDate.format('MM-DD HH:mm')
  } else {
    return msgDate.format('YYYY-MM-DD')
  }
}
</script>

<style lang="scss" scoped>
.message-center-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .page-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.message-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;

  .stat-item {
    background: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .stat-number {
      font-size: 28px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;

      &.unread {
        color: #e6a23c;
      }
    }

    .stat-label {
      color: #666;
      font-size: 14px;
    }
  }
}

.filter-section {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  .tab-badge {
    margin-left: 4px;
  }
}

.search-section {
  margin-bottom: 20px;
}

.message-list {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }
}

.message-item {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
  position: relative;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  &.unread {
    background: linear-gradient(135deg, #fff 0%, #f0f9ff 100%);
    
    .message-title {
      font-weight: 600;
    }
  }

  &.selected {
    border-color: #409eff;
    background-color: #f0f9ff;
  }

  &.urgent {
    border-left: 4px solid #f56c6c;
  }

  .item-checkbox {
    margin-right: 12px;
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
  }

  .message-icon {
    margin-right: 16px;
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
    flex-shrink: 0;
    position: relative;

    .urgent-indicator {
      position: absolute;
      top: -2px;
      right: -2px;
      width: 12px;
      height: 12px;
      background: #f56c6c;
      color: white;
      border-radius: 50%;
      font-size: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
    }
  }

  .message-content {
    flex: 1;
    min-width: 0;

    .message-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;

      .message-title {
        margin: 0;
        font-size: 16px;
        color: #333;
        line-height: 1.4;
        flex: 1;
        margin-right: 16px;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .message-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 4px;
        flex-shrink: 0;

        .message-time {
          color: #999;
          font-size: 12px;
          white-space: nowrap;
        }
      }
    }

    .message-summary {
      margin: 0 0 12px 0;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .message-extras {
      margin-bottom: 12px;

      .extra-item {
        display: inline-flex;
        align-items: center;
        margin-right: 16px;
        font-size: 12px;

        .extra-label {
          color: #999;
        }

        .extra-value {
          color: #333;
          font-weight: 500;

          &.amount {
            color: #e6a23c;
          }
        }
      }
    }

    .message-footer {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }

  .message-actions {
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
    margin-left: 12px;
    flex-shrink: 0;
  }

  .unread-indicator {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 8px;
    height: 8px;
    background-color: #409eff;
    border-radius: 50%;
  }

  .pinned-indicator {
    position: absolute;
    top: 12px;
    right: 12px;
    color: #e6a23c;
  }
}

.load-more {
  text-align: center;
  margin-top: 24px;
}

.message-detail {
  .detail-header {
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    .detail-meta {
      display: flex;
      align-items: center;
      gap: 12px;

      .detail-time {
        color: #999;
        font-size: 14px;
        margin-left: auto;
      }
    }
  }

  .detail-content {
    line-height: 1.6;
    color: #333;
    margin-bottom: 16px;

    :deep(img) {
      max-width: 100%;
      height: auto;
    }
  }

  .detail-extras {
    margin-bottom: 16px;
  }

  .detail-attachments {
    margin-bottom: 16px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #666;
    }

    .attachment-list {
      display: flex;
      flex-direction: column;
      gap: 8px;

      .attachment-item {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        background-color: #f5f7fa;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s ease;

        &:hover {
          background-color: #e4e7ed;
        }

        .el-icon {
          margin-right: 8px;
          color: #409eff;
        }

        .attachment-size {
          margin-left: auto;
          color: #999;
          font-size: 12px;
        }
      }
    }
  }

  .detail-links {
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #666;
    }

    .link-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;

    h1 {
      text-align: center;
    }

    .page-actions {
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .message-stats {
    grid-template-columns: 1fr;
    gap: 12px;

    .stat-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      text-align: left;
      padding: 16px;

      .stat-number {
        font-size: 24px;
        margin-bottom: 0;
      }
    }
  }

  .filter-section {
    padding: 0 10px;
  }

  .message-item {
    padding: 12px;

    .item-checkbox {
      position: absolute;
      top: 12px;
      right: 12px;
      margin: 0;
    }

    .message-icon {
      margin-right: 0;
      margin-bottom: 8px;
      align-self: flex-start;
    }

    .message-content {
      .message-header {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;

        .message-meta {
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
        }
      }
    }

    .message-actions {
      margin-left: 0;
      margin-top: 12px;
      justify-content: center;
    }

    .unread-indicator {
      top: 12px;
      right: 50px;
    }

    .pinned-indicator {
      top: 8px;
      right: 50px;
    }
  }
}
</style> 